package com.joe.learn.dubbo.callback.consumer;

import com.joe.learn.dubbo.callback.api.CallbackListener;
import com.joe.learn.dubbo.callback.api.CallbackService;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.ArrayDeque;
import java.util.Queue;
import java.util.Scanner;

public class Consumer {

    /**
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) throws Exception {
        final Queue<String> list = new ArrayDeque<String>();
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
                new String[]{"classpath:consumer.xml"});
        context.start();

        // 参数回调
        final CallbackService callbackService = (CallbackService) context.getBean("callbackService");
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    String top = list.poll();
                    if (top == null) {
                        continue;
                    }
                    callbackService.addListener(top, new CallbackListener() {
                        @Override
                        public void changed(String msg) {
                            System.out.println("callback1:" + msg);
                        }
                    });
                }
            }
        }).start();

        do {
            String str = readDataFromConsole("Please input string:");
            list.add(str);
            //System.out.println("The information from console:" + str);
        } while (true);
    }

    private static String readDataFromConsole(String prompt) {
        Scanner scanner = new Scanner(System.in);
        System.out.println(prompt);
        return scanner.nextLine();
    }
}